package com.example.fw;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;

import com.example.tests.GroupObject;

public class GroupHelper extends HelperWithWebDriverBase {

	public GroupHelper(ApplicationManager manager) {
		super(manager);
	}

	public Set<GroupObject> getGroups() {
		manager.getNavigationHelper().openGroupListPage();
		WebElement form = findElements(By.tagName("form")).get(1);
		List<WebElement> checkboxes = form.findElements(By.name("selected[]"));
		Set<GroupObject> groups = new HashSet<GroupObject>();
		for (WebElement checkbox : checkboxes) {
			String title = checkbox.getAttribute("title");
			//
			title = title.substring("Select (".length(), title.length()-")".length());
			//
			GroupObject group = new GroupObject()
					.setName(title)
					.setId(checkbox.getAttribute("value"));
			groups.add(group);
		}
		return groups;
	}

	public void createGroup(GroupObject groupObject) {
		manager.getNavigationHelper().openGroupListPage();
		initGroupCreation();
		fillGroupForm(groupObject);
		submitGroupCreation();
		returnToGroupListPage();
	}

	public void deleteGroup(int i) {
		manager.getNavigationHelper().openGroupListPage();
		checkGroup(i);
		click(By.name("delete"));
		returnToGroupListPage();
	}

	public void modifyGroup(int i, GroupObject groupObject) {
		manager.getNavigationHelper().openGroupListPage();
		initGroupModification(i);
		fillGroupForm(groupObject);
		submitGroupModification();
		returnToGroupListPage();
	}

	private void checkGroup(int i) {
		click(By.xpath(".//*[@id='content']/form[2]/input[" + i + "]"));
	}

	private void initGroupCreation() {
		click(By.name("new"));
	}

	private void initGroupModification(int i) {
		checkGroup(i);
		click(By.name("edit"));
	}

	private void fillGroupForm(GroupObject groupObject) {
		type(By.name("group_name"), groupObject.name);
		type(By.name("group_header"), groupObject.header);
		type(By.name("group_footer"), groupObject.footer);
	}

	private void submitGroupCreation() {
		click(By.name("submit"));
	}

	private void submitGroupModification() {
		click(By.name("update"));

	}

	private void returnToGroupListPage() {
		click(By.linkText("group page"));
	}

}
